package org.ring.common.transport;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * @since 2023-10-27 12:06
 */
public class NettyDecoder extends ByteToMessageDecoder {
    private Codec codec;

    public NettyDecoder(Codec codec) {
        this.codec = codec;
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        // decode object.
        for (; in.isReadable(); ) {
            int readerIndex = in.readerIndex();
            Object msg = codec.decode(in);
            if (msg == null) {
                in.readerIndex(readerIndex);
                break;
            }
            out.add(msg);
        }
    }

}
